import { Modal } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import ModelPreviewer from './ModelPreviewer';
import { CMEVENTS } from '@amcax/base';
import { userEvents } from '../../../../../../module';

export default function ModelPreviewModal() {
  const [open, setOpen] = useState<boolean>(false);
  const [url, setUrl] = useState<string>();
  const modelPreviewer = useRef<ModelPreviewer>();

  useEffect(() => {
    modelPreviewer.current = ModelPreviewer.getInstance();
    registerEvents();
    return () => {
      modelPreviewer.current.dispose();
    };
  }, []);

  useEffect(() => {
    if (open && url && url !== '') {
      loadObj(url);
    } else {
      modelPreviewer.current.dispose();
    }
  }, [open, url]);

  const registerEvents = () => {
    userEvents.on(CMEVENTS.COMPONENT_PREVIEW, ({ url }) => {
      setUrl(url);
      setOpen(true);
    });
  };

  const loadObj = async (url: string) => {
    const container = document.getElementById('model-viewer');
    container.innerHTML = '';
    modelPreviewer.current.init(container);
    modelPreviewer.current.loadObj(url);
    modelPreviewer.current.animate();
  };

  return (
    <Modal
      title='模型预览'
      width={650}
      onOk={() => setOpen(false)}
      onCancel={() => setOpen(false)}
      footer={null}
      open={open}>
      <div id='model-viewer'></div>
    </Modal>
  );
}
